package com.fancon.android.gardenjokesx.adapter;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.fancon.android.emoji.widget.RichTextView;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.activity.M05Activity;
import com.fancon.android.gardenjokesx.activity.ProfileActivity;
import com.fancon.android.gardenjokesx.entity.Comment;
import com.fancon.android.gardenjokesx.entity.ReportErrors;
import com.fancon.android.gardenjokesx.rpc.GardenJokesApiConnect;
import com.fancon.android.gardenjokesx.rpc.JsonPaser;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.StringUtil;
import com.fancon.android.gardenjokesx.utils.TimeUtil;
import com.fancon.android.ui.widget.ImageCacheView;

public class ListCommentAdapter extends BaseAdapter implements
		OnGestureListener {

	private static final int SWIPE_MIN_DISTANCE = 120;
	private static final int SWIPE_MAX_OFF_PATH = 250;
	private static final int SWIPE_THRESHOLD_VELOCITY = 200;
	private GestureDetector gestureDetector;
	private LayoutInflater mInflater;
	private ArrayList<Comment> mListComment;
	private String currentUserID;
	private int mPosition;
	private Activity mContext;
	private Button btnDelete;
	private TextView tvtime;
	private View curentItem;
	private boolean btnVisible = false;
	private static final int NONE = 0;
	private static final int DOWN = 1;
	private static final int FLING = 2;
	private static final int SCROLL = 3;
	private int mode = NONE;
	private int screenID;

	public ListCommentAdapter(Activity context, ArrayList<Comment> listComment,
			String userid, int scrID) {
		mListComment = listComment;
		mInflater = LayoutInflater.from(context);
		mContext = context;
		currentUserID = userid;
		screenID = scrID;
	}

	public int getCount() {
		return mListComment.size();
	}

	public Object getItem(int position) {
		return mListComment.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(final int position, View convertView, ViewGroup parent) {

		gestureDetector = new GestureDetector(this);
		ViewHolder holder;
		final Comment comment = mListComment.get(position);
		View vi = convertView;
		if (vi == null) {
			vi = mInflater.inflate(R.layout.m05_item_comment, null);
			holder = new ViewHolder();
			holder.imgAvatar = (ImageCacheView) vi
					.findViewById(R.id.m05_imgAvar);
			holder.txtUserName = (RichTextView) vi
					.findViewById(R.id.m05_tvUserName);
			holder.txtComment = (RichTextView) vi
					.findViewById(R.id.m05_tvComment);
			holder.txtTimePost = (TextView) vi
					.findViewById(R.id.m05_tvTimePost);
			holder.btnDelete = (Button) vi.findViewById(R.id.m05_btnDelete);
			vi.setTag(holder);
		} else {
			holder = (ViewHolder) vi.getTag();
		}
		holder.imgAvatar.loadImage(StringUtil.processImageLink(comment.getUrl_image()));
		holder.txtTimePost.setText(TimeUtil.getTimeCount(
				comment.getTime_post(), mContext));
		try {
			holder.txtUserName.setText(URLDecoder.decode(
					comment.getUser_name(), "UTF-8"));
			String commentx = URLDecoder.decode(comment.getContent(), "UTF-8");
			Log.d("Comment ", commentx);
			holder.txtComment.setText(URLDecoder.decode(comment.getContent(),
					"UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			System.out.print(e.getMessage());
		}
		//@binhbt-comment
		//need use multi thread to improve speed
		holder.btnDelete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (deleteComment(mListComment.get(position).getComment_id(),
						currentUserID)) {
					if (screenID == Constant.M03_1 || screenID == Constant.M03
							|| screenID == Constant.M04_L
							|| screenID == Constant.T02_L) {
						M05Activity.m05IsChange = true;
					}

					((M05Activity) mContext).refresh();
				}
			}
		});
		holder.imgAvatar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//@binhbt-comment
				Intent intent = new Intent(mContext, ProfileActivity.class);
				intent.putExtra(Constant.USER_ID_VIEW, comment.getUser_id());
				mContext.startActivity(intent);
			}
		});
		holder.txtUserName.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//@binhbt-comment
				Intent intent = new Intent(mContext, ProfileActivity.class);
				intent.putExtra(Constant.USER_ID_VIEW, comment.getUser_id());
				mContext.startActivity(intent);
			}
		});
		vi.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				Log.d("test test", "vao ontouch");
				curentItem = arg0;
				mPosition = position;
				switch (arg1.getAction() & MotionEvent.ACTION_MASK) {

				case MotionEvent.ACTION_DOWN:
					mode = DOWN;
					Log.d("vao down", "downwnwnw");
					if (btnVisible == true) {
						btnDelete.setVisibility(View.GONE);
						tvtime.setVisibility(View.VISIBLE);
						btnVisible = false;
						return false;
					}
					break;
				case MotionEvent.ACTION_UP:
					Log.d("vao up", "vao up up up");
					String text = "@"
							+ mListComment.get(mPosition).getUser_name() + " ";
					if (btnVisible == false && mode == DOWN) {
						if (M05Activity.mEditComment.getText().length() == 0) {
							M05Activity.mEditComment.append(text);
						} else {
							if (M05Activity.mEditComment.getText().length() > 0) {
								M05Activity.mEditComment.append(" " + text);
							}
						}
					}
					mode = NONE;
					break;
				}
				return gestureDetector.onTouchEvent(arg1);
			}
		});
		return vi;
	}

	static class ViewHolder {
		ImageCacheView imgAvatar;
		RichTextView txtUserName;
		TextView txtTimePost;
		RichTextView txtComment;
		Button btnDelete;
	}

	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		mode = DOWN;
		return true;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		// TODO Auto-generated method stub
		Log.d("test test", "vao onFling");
		btnDelete = (Button) curentItem.findViewById(R.id.m05_btnDelete);
		tvtime = (TextView) curentItem.findViewById(R.id.m05_tvTimePost);
		try {
			if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
				return false;
			// right to left swipe
			if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
					&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
				mode = FLING;
				if (mListComment.get(mPosition).getUser_id()
						.equals(currentUserID)) {
					btnDelete.setVisibility(View.VISIBLE);
					tvtime.setVisibility(View.GONE);
					btnVisible = true;
				}
			} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
					&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
				mode = FLING;
				if (mListComment.get(mPosition).getUser_id()
						.equals(currentUserID)) {
					btnDelete.setVisibility(View.VISIBLE);
					tvtime.setVisibility(View.GONE);
					btnVisible = true;
				}
			}
		} catch (Exception e) {
			System.out.print(e.getMessage());
		}

		return true;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		mode = SCROLL;
		return true;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return true;
	}

	public boolean deleteComment(String comment_id, String user_id) {

		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
		nameValuePairs.add(new BasicNameValuePair("comment_id", comment_id));
		nameValuePairs.add(new BasicNameValuePair("user_id", user_id));
		GardenJokesApiConnect api = new GardenJokesApiConnect(mContext);
		String result = api.execGet(mContext, GardenJokesApiConnect.GROUP_M,
				"deleteComment", nameValuePairs);
		Log.d("list comment", result);
		JsonPaser json = new JsonPaser();
		ReportErrors report = json.getReport(result);
		return report.isIs_success();
	}
}
